class_name WoodCrate
extends RigidBody2D

@export var drop_config: DropConfig
@onready var unit_born_point: UnitBornPoint = $UnitBornPoint
var crate_data: CrateData
@onready var hurt_collision_shape_2d: CollisionShape2D = $HitArea/CollisionShape2D
@onready var body_collision_shape: CollisionShape2D = $BodyCollisionShape
@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var buff_parent: Node2D = $BuffParent

@export var born_unit_data: UnitBaseData
var level: Level = null
	

func disable_physics():
	if crate_data.is_broken: return
	
	hurt_collision_shape_2d.disabled = true
	body_collision_shape.disabled = true
	gravity_scale = 0.0
	

func enable_physics():
	if crate_data.is_broken: return
	
	hurt_collision_shape_2d.disabled = false
	body_collision_shape.disabled = false
	gravity_scale = 1.0


func _ready() -> void:
	level = get_tree().current_scene as Level
	
	if not crate_data:
		crate_data = CrateData.new()
	crate_data.id = self.name


func take_hit(hit_data: HitData, source: Node2D = null):
	AudioManager.play_sound("sfx_wood_break")
	set_broken()
	
	var level: Level = get_tree().current_scene as Level
	level.emit_particle("particle_crate_crumbs", global_position)
	level.start_drop(drop_config, global_position)
	
	if born_unit_data:
		born_unit()
	

func born_unit():
	var unit_data = born_unit_data.duplicate(true) as UnitBaseData
	unit_data.home_position = global_position
	unit_data.pos = global_position
	
	var level = get_tree().current_scene as Level
	level.level_data.units_data.append(unit_data)
	
	level.create_unit_by_unit_data(unit_data) 


func init_by_data(data: CrateData):
	crate_data = data
	
	if crate_data.is_broken:
		set_broken()
		

func set_broken():
	gravity_scale = 0.0
	hurt_collision_shape_2d.disabled = true
	body_collision_shape.disabled = true
	sprite_2d.visible = false	
	crate_data.is_broken = true
	

func add_buff(buff_name: String, sender: Node2D):
	var buff_inst = (ResourceManager.get_resource(buff_name) as PackedScene).instantiate()
	buff_inst.holder = self
	buff_parent.add_child(buff_inst)
	buff_inst.sender = sender
